package com.dinghui.pay.controller.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.dinghui.pay.common.ResponseResult;
import com.dinghui.pay.pojo.TbOrder;
import com.dinghui.pay.pojo.TbUser;
import com.dinghui.pay.pojo.param.LoginParam;
import com.dinghui.pay.pojo.param.PayOrderParam;
import com.dinghui.pay.pojo.param.UpdateOrderStatusParam;
import com.dinghui.pay.service.OrderService;
import com.dinghui.pay.service.UserService;
import com.dinghui.pay.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author: trt
 * @description:
 * @create: 2021-06-05 19:46
 */
// android 支付宝业务接口
@RestController
@RequestMapping("/api/alipay/app")
public class AppController {
    /**
     *  正式： https://open.alipay.com/platform/appManage.htm?from=createMenuPage&create=1-ab6b-4f9c4e5c01f11487667522647#/create/1-ab6b-4f9c4e5c01f11487667522647
     *  android开通沙箱 https://open.alipay.com/platform/appDaily.htm?tab=info
     */

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private OrderService orderService;

    @Value("${alipay.app.app-id}")
    private String app_appId;

    @Value("${alipay.app.public-key}")
    private String app_publicKey;

    @Value("${alipay.app.private-key}")
    private String app_privateKey;

    @Value("${alipay.microApp.gateway}")
    private String gateway;

    /**
     * 登录
     */
    @PostMapping("login")
    public ResponseResult login(@RequestBody LoginParam param) throws Exception {
        //用户登录
        long userId = userService.login(param);

        //生成token
        String token = jwtUtils.generateToken(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());

        return ResponseResult.success(map);
    }

    /**
     * app sdk :https://opendocs.alipay.com/open/54/106370
     */
    /**
     * app付款
     */
    @PostMapping("/appPayOrder")
    public ResponseResult appPayOrder(@RequestBody PayOrderParam param, @RequestHeader HashMap header) {
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = param.getOrderId();
        TbUser user = new TbUser();
        user.setUserId(userId);
        long count = userService.getCount(user);
        //判断用户是否存在
        if (count == 0) {
            return ResponseResult.error("用户不存在");
        }
        //获取用户账号的openid字符串
        String openId = userService.getOne(user).getOpenId();

        //判断用户是否拥有这个订单，并且订单是未支付状态
        TbOrder order = new TbOrder();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        count = orderService.getCount(order);
        if (count == 0) {
            return ResponseResult.error("不是有效的订单");
        }

        // todo 验证购物券是否有效
        // todo 验证团购活动是否有效

        //查询订单详情信息
        order = new TbOrder();
        order.setId(orderId);
        order = orderService.getOne(order); //订单对象
        String amount = order.getAmount() + ""; //订单金额

        try {
            AlipayClient client = new DefaultAlipayClient(gateway, app_appId, app_privateKey, "json", "UTF-8", app_publicKey, "RSA2");
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody("我是测试数据");
            model.setSubject("App支付测试Java");
            model.setOutTradeNo(order.getCode());
            model.setTimeoutExpress("30m");
            model.setTotalAmount(amount);
            model.setProductCode("QUICK_MSECURITY_PAY");
            request.setNotifyUrl("http://www.demo.com");
            request.setBizModel(model);

            AlipayTradeAppPayResponse response = client.sdkExecute(request);
            if (response.isSuccess()) {
                //String prepayId = response.getTradeNo();
                //更新本地商品订单信息，但是不更新商品订单状态
                //order.setPrepayId(prepayId); //保存支付订单ID
                order.setPaymentType(2);
                order.setId(order.getId()); //支付类型
                orderService.update(order); // 查询条件
                return ResponseResult.success("orderString", response.getBody());
            } else {
                return ResponseResult.error("支付订单创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("支付宝支付模块故障");
        }
    }
    // android实现支付调用： https://opendocs.alipay.com/open/204/105296


    /**
     * 查询支付订单状态
     * 的参数 https://opendocs.alipay.com/apis/api_1/alipay.trade.query
     * out_trade_no：商户订单ID
     * trade_no: 支付订单ID
     * query_options: 查询参数
     */
    // 更新商品订单状态 （主动更新订单状态）
    @PostMapping("/appUpdateOrderStatus")
    public ResponseResult appUpdateOrderStatus(@RequestBody UpdateOrderStatusParam param,
                                            @RequestHeader HashMap header) {
        String token = header.get("token").toString();
        int userId = Integer.parseInt(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = param.getOrderId();
        TbOrder order = new TbOrder();
        order.setUserId(userId);
        order.setId(orderId);
        int count = orderService.getCount(order);
        if (count == 0) {
            return ResponseResult.error("用户与订单不匹配");
        }
        order = orderService.getOne(order);
        String code = order.getCode();

        try {
            AlipayClient client = new DefaultAlipayClient(
                    gateway,
                    app_appId,
                    app_privateKey,
                    "json",
                    "UTF-8",
                    app_publicKey,
                    "RSA2"
            );
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\"" + code + "\"," +
                    "      \"query_options\":[" +
                    "        \"TRADE_SETTLE_INFO\"" +
                    "      ]" +
                    "  }");
            AlipayTradeQueryResponse response = client.execute(request);
            if (response.isSuccess()) {
                String tradeStatus = response.getTradeStatus();
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    TbOrder tbOrder = new TbOrder();
                    tbOrder.setCode(code); // 查询条件
                    tbOrder.setStatus(2); // 修改值
                    tbOrder.setPaymentType(1); // 修改值
                    tbOrder.setPrepayId(response.getTradeNo());
                    orderService.updateOrderStatus(order);
                    return ResponseResult.success("订单状态已修改");
                } else {
                    return ResponseResult.success("订单状态未修改");
                }
            }
            return ResponseResult.success("订单状态未修改");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("查询支付订单失败");
        }
    }

}